package com.yjf.ljr.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.R.xml;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.AppNewsRefreshDataClass;
import com.yjf.ljr.dataclass.NewsDataClass;
import com.yjf.ljr.dataclass.NewsDataClass.NewsItem;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

public class NewsActivity extends IjActivity {

	@ID("xlvNews")
	private XListView mXlvNews;
	private CommonAdapter mCommonAdapter;
	private List<NewsItem> mData = new ArrayList<NewsItem>();

	private boolean mIsLoadingMore = false;
	private final int mPageSize = 10;
	private int mCurPage = 1;
	String data = "";
	private static final String NEWLISTS = "newlists";
	private static final String NEWLISTSTIME = "newliststime";
	private String updateTime;// 上次更新的时间

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news);

		initControls();

		showProgressDialog();
		new CheckAppNewsRefresh().execute();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/** 初始化控件 **/
	private void initControls() {
		setLeftBtnClick();
		setTitleStr("新闻公告");
		mCommonAdapter = new CommonAdapter(this, mData, R.layout.item_news, ViewHolder.class, mHandleCallBack);
		mXlvNews.setAdapter(mCommonAdapter);
		mXlvNews.setPullLoadEnable(true);
		mXlvNews.setPullRefreshEnable(true);
		mXlvNews.mFooterView.hide(); // 隐藏更多
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mXlvNews.setRefreshTime(sdf.format(new Date()));
		mXlvNews.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				mCurPage = 1;
				mIsLoadingMore = true;
				new CheckAppNewsRefresh().execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new CheckAppNewsRefresh().execute();
			}
		});
	}

	/***
	 * 
	 * @author 检查新闻列表是否要更新
	 *
	 */
	class CheckAppNewsRefresh extends AsyncTask<Void, Void, String> {
		private AppNewsRefreshDataClass dc = new AppNewsRefreshDataClass();

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject requestObject = new RequestObject();
			updateTime = (String) SPreferences.getData(mContext, "0", NEWLISTSTIME);
			requestObject.method = "appNewsRefresh";
			requestObject.map.put("updateTime", updateTime);
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if ("1".equals(dc.code)) {
				new NewsGetTask(false, "").execute();
			} else {
				new NewsGetTask(false, "").execute();
			}
		}
	}

	/*
	 * AsyncTask定义了三种泛型类型 Params，Progress和Result •doInBackground(Params… params)
	 * •publicProgress(Progress… progress) •onPostExecute(Result result)
	 */
	class NewsGetTask extends AsyncTask<Void, Void, String> {

		// private int pageSize;
		// private int curPage;
		private boolean isAdd = false;
		private NewsDataClass dc = new NewsDataClass();
		private String data;

		public NewsGetTask(boolean isAdd, String data) {
			super();
			// this.pageSize = pageSize;
			// this.curPage = curPage;
			this.isAdd = isAdd;
			this.data = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			String failStr = "";
			String xmlStr = "";
			RequestObject reqObj = new RequestObject();
			reqObj.method = "getNewsList";// getNewsList.htm
			// reqObj.map.put("pageSize", pageSize);
			// reqObj.map.put("pageNumber", curPage);
			// reqObj.map.put("type", "2");

			if (TextUtils.isEmpty(data)) {
				String requestStr = RequestBuilder.build(reqObj);
				xmlStr = IjConnect.getRequestResult(requestStr);
				if (!TextUtils.isEmpty(xmlStr)) {

					SPreferences.saveData(mContext, xmlStr, NEWLISTS);
				}
			} else {
				xmlStr = data;
			}
			dc.getDataClassFromStr(xmlStr);
			if (dc.code == null) {
				failStr = getResources().getString(R.string.loaddata_exception);
			} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
				failStr = dc.msg;
			}
			return failStr;
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
				mData.clear();
				mCommonAdapter.notifyDataSetChanged();
			} else {
				if (!isAdd) {
					mData.clear();
				}
				if (dc.newsList != null && dc.newsList.size() > 0) {
					if (!TextUtils.isEmpty(dc.updateTime)) {
						SPreferences.saveData(mContext, dc.updateTime, NEWLISTSTIME);
					}
					mData.addAll(dc.newsList);
					mCommonAdapter.notifyDataSetChanged();

					// if (mData.size() <= (dc.totalPage - 1) * pageSize) {
					// mXlvNews.mFooterView.show();
					// } else {
					// mXlvNews.mFooterView.hide();
					// }
				}
			}
			mXlvNews.stopRefresh();
			mXlvNews.stopLoadMore();
			dismissProgressDialog();
			mIsLoadingMore = false;
		}
	}

	public static class ViewHolder {
		TextView tvNewsTitle;

	}

	private HandleCallBack mHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(final int position, final View convertView, ViewGroup parent, Object holder, Object item) {
			final NewsItem info = (NewsItem) item;
			ViewHolder h = (ViewHolder) holder;
			AppUtil.setViewText(h.tvNewsTitle, info.title);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent i = new Intent(NewsActivity.this, NewsDetailActivity.class);
					i.putExtra("newsDetailId", info.id);
					startActivity(i);
				}
			});
		}
	};
}
